<?php

namespace App\Console\Commands;

use App\Models\Warranty;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class CarOwner extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:CarOwner';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $this->statOldData(date('Y-m-d', strtotime('-1 day')), date('Y-m-d'));
        return 0;
    }

    public function statOldData($start_date, $end_date)
    {
        $start_month = strtotime($start_date);
        $end_month = strtotime($end_date);
        for ($time = $start_month; $time < $end_month; $time += 86400) {
            $start_time = date('Y-m-d', $time);
            $end_time = date('Y-m-d', $time + 86400);
            $data = Warranty::where('approved_date', '>=', $start_time)
                ->where('approved_date', '<', $end_time)
                ->where('approved', 1)->get();
            if (empty($data) || $data->isEmpty()) {
                continue;
            }
            foreach ($data as $item) {
                if (empty($item->phone_number)) {
                    continue;
                }
                $owner = DB::table('xpel_car_owner')->where('phone_number', $item->phone_number)->first();
                if (!empty($owner)) {
                    continue;
                }

                $province = DB::table('province_master')->where('id', $item->province_id)->first();
                if (empty($province)) {
                    continue;
                }

                $city = DB::table('cities')->where('id', $item->city)->first();
                if (empty($city)) {
                    continue;
                }

                $insertData = [
                    'user_name'  => $item->first_name,
                    'phone_number' => $item->phone_number,
                    'address'   => $item->address,
                    'province'  => $province->simplified_chiness_value,
                    'city'      => $city->simplified_chiness_value,
                    'province_id' => $item->province_id,
                    'city_id'     => $item->city,
                ];
                DB::table('xpel_car_owner')->insert($insertData);
            }
        }
    }
}
